/*
 * UserOrdersServlet.java
 * 作用：处理用户"我的订单"页面的请求，获取用户作为买家和卖家的所有订单。
 */
package com.campustradingwall.controller.user;

import com.campustradingwall.dao.OrderDao;
import com.campustradingwall.dao.RatingDao;
import com.campustradingwall.model.Order;
import com.campustradingwall.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/orders")
public class UserOrdersServlet extends HttpServlet {
    private OrderDao orderDao = new OrderDao();
    private RatingDao ratingDao = new RatingDao();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");

        // 获取我接收的订单
        List<Order> receivedOrders = orderDao.getReceivedOrdersBySellerId(user.getId());
        
        // 获取我发送的订单
        List<Order> sentOrders = orderDao.getSentOrdersByBuyerId(user.getId());

        // 检查我发送的订单（已完成）是否已被评价
        for (Order order : sentOrders) {
            if ("completed".equals(order.getStatus())) {
                boolean isRated = (ratingDao.getRatingByOrderId(order.getId()) != null);
                order.setRated(isRated);
            }
        }

        request.setAttribute("receivedOrders", receivedOrders);
        request.setAttribute("sentOrders", sentOrders);
        
        // 处理消息提示
        String message = (String) request.getSession().getAttribute("message");
        if (message != null) {
            request.setAttribute("message", message);
            request.getSession().removeAttribute("message");
        }

        request.getRequestDispatcher("/user/orders.jsp").forward(request, response);
    }
} 